from django.shortcuts import render, get_object_or_404, redirect
from blogApp.models import Post
from blogApp.views import send_myself_email
from django.views.decorators.http import require_POST
from .models import Comment,sonComment
from .forms import CommentForm,sonCommentForm
from django.http import HttpResponse
import json
 
@require_POST
def post_comment(request, post_pk):
    comment = CommentForm(request.POST)
    if comment.is_valid():
        post = get_object_or_404(Post, pk=post_pk)
        newcomment = comment.save(commit=False)
        newcomment.post = post
        newcomment.save()
        print("commit success")
        re_context= {
            "name":request.POST.get("name"),
            "title" :post.title,
            "body":request.POST.get("text")
        }
        send_myself_email("1654262479@qq.com", re_context)
        print("email success")
        return HttpResponse("")
    else:
        context = {
            'body_error': comment.errors.get('text'),
            'username_error': comment.errors.get('name'),
            'email_error': comment.errors.get('email'),
            'url_error': comment.errors.get('url'),
            'qq_error': comment.errors.get('qqnumber'),
            'picurl_error': comment.errors.get('picurl'),
        }
        print("comment errors")
        return HttpResponse(json.dumps(context,ensure_ascii=False),content_type='application/json')

 
@require_POST
def reply_comment(request, comment_pk):
    reply = sonCommentForm(request.POST)
    if reply.is_valid():
        comment = get_object_or_404(Comment, pk=comment_pk)
        newcomment = reply.save(commit=False)
        newcomment.p_comment = comment
        newcomment.save()
        print("success")
        re_context= {
            "name":request.POST.get("name"),
            "title" :comment.post.title+" 回复："+comment.name,
            "body":request.POST.get("text")
        }
        send_myself_email("1654262479@qq.com",re_context)
        return HttpResponse("")
    else:
        context = {
            'body_error': reply.errors.get('text'),
            'username_error': reply.errors.get('name'),
            'email_error': reply.errors.get('email'),
            'url_error': reply.errors.get('url'),
            'qq_error': reply.errors.get('qqnumber'),
            'picurl_error': reply.errors.get('picurl'),
        }
        return HttpResponse(json.dumps(context,ensure_ascii=False),content_type='application/json')